package com.yeskery.nut.bean.scheduling;

import com.yeskery.nut.core.ThreadPool;
import com.yeskery.nut.util.CronSequenceGenerator;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Cron定时调度任务
 * @author YESKERY
 * 2024/6/5
 */
public class CronScheduledJob implements ScheduledJob {

    /** cron序列构造器 */
    private final CronSequenceGenerator cronSequenceGenerator;

    /**
     * 构建Cron定时调度任务
     * @param cronSequenceGenerator cron序列构造器
     */
    public CronScheduledJob(CronSequenceGenerator cronSequenceGenerator) {
        this.cronSequenceGenerator = cronSequenceGenerator;
    }

    @Override
    public void handle(ThreadPool threadPool, Runnable runnable) throws Exception {
        Date now = new Date();
        long delay = cronSequenceGenerator.next(now).getTime() - now.getTime();
        if (delay < 0) {
            delay = 0;
        }
        threadPool.getScheduledThreadPool().schedule(() -> {
            runnable.run();
            try {
                new CronScheduledJob(cronSequenceGenerator).handle(threadPool, runnable);
            } catch (Exception e) {
                throw new ScheduledException("ScheduledJob[" + CronScheduledJob.class.getName() + "] Execute Fail.", e);
            }
        }, delay, TimeUnit.MILLISECONDS);
    }
}
